
//***********************************************
//
//      Filename: SEnc.java
//
//        Author: wwb
//        Mails: 1274860621@qq.com
//        Create: 2018-06-17 09:07:32
// Last Modified: 2018-06-17 09:07:32
//***********************************************
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.security.PrivateKey;
import java.security.PublicKey;

public class SEnc {
    public SEnc(){}
    public String jiami(String s) throws Exception{
        FileInputStream f1=new FileInputStream("Bpub.dat");
        ObjectInputStream b1=new ObjectInputStream(f1);
        PublicKey pbk=(PublicKey)b1.readObject( );
//读取自己的DH私钥
        FileInputStream f3=new FileInputStream("Apri.dat");
        ObjectInputStream b2=new ObjectInputStream(f3);
        PrivateKey prk=(PrivateKey)b2.readObject();
        // 执行密钥协定
        KeyAgreement ka=KeyAgreement.getInstance("DH");
        ka.init(prk);
        ka.doPhase(pbk,true);
        //生成共享信息
        byte[ ] sb=ka.generateSecret();
//        for(int i=0;i<sb.length;i++){
//            System.out.print(sb[i]+",");//sb为新密钥
//        }

//       FileInputStream f=new FileInputStream("key1.dat");
//        ObjectInputStream b=new ObjectInputStream(f);
       // Key k=(Key)b.readObject( );
        //Key k=sb;
//        KeyGenerator kg=KeyGenerator.getInstance("DESede");
//        kg.init(168);
        SecretKeySpec k = new SecretKeySpec(sb, 0,24,"DESede");
        Cipher cp=Cipher.getInstance("DESede");
        cp.init(Cipher.ENCRYPT_MODE, k);
        byte ptext[]=s.getBytes("UTF8");
//        for(int i=0;i<ptext.length;i++){
//            System.out.print(ptext[i]+",");
//        }
        byte ctext[]=cp.doFinal(ptext);
        String a="";
        for(int i=0;i<ctext.length;i++){
            a+=ctext[i] +",";
            //    System.out.print(a);
        }
        FileOutputStream f2=new FileOutputStream("SEnc.dat");
        f2.write(ctext);
        return a;
    }
}
